﻿using UnityEngine;
using System.Collections;

public class AnimationTrigger : MonoBehaviour
{

    public Animation target;
    public bool isReverse = false;
    public int animationIndex = 0;
    public string animationName;

    void Start()
    {
        if (target == null) //默认触发自身的Animation
        {
            target = GetComponent<Animation>();
        }
    }


    /// <summary>
    /// 按序列
    /// </summary>
    public void TriggerByIndex()
    {
        int index = 0;
        foreach (AnimationState ani in target)
        {
            if (index == animationIndex)
            {
                if (isReverse)
                {
                    ani.speed = -1f;
                    ani.normalizedTime = 1f;
                }
                else
                {
                    ani.speed = 1;
                    ani.time = 0;
                }
                target.CrossFade(ani.name);
                break;
            }
            else
            {
                index++;
            }
        }
    }

    public void TriggerByIndexReverse()
    {
        int index = 0;
        foreach (AnimationState ani in target)
        {
            if (index == animationIndex)
            {
                if (isReverse)
                {
                    ani.speed = 1f;
                    ani.normalizedTime = 0f;
                }
                else
                {
                    ani.speed = -1f;
                    ani.time = 1f;
                }
                target.CrossFade(ani.name);
                break;
            }
            else
            {
                index++;
            }
        }
    }

    public void TriggerByName()
    {
        AnimationState ani = target[animationName];
        if (isReverse)
        {
            ani.speed = -1f;
            ani.normalizedTime = 1f;
        }
        else
        {
            ani.speed = 1;
            ani.time = 0;
        }
        target.CrossFade(ani.name);
    }

    public void TriggerByNameReverse()
    {
        AnimationState ani = target[animationName];
        if (isReverse)
        {
            ani.speed = 1f;
            ani.normalizedTime = 0f;
        }
        else
        {
            ani.speed = -1f;
            ani.time = 1f;
        }
        target.CrossFade(ani.name);
    }
}
